/**
 * 要用到节点池的脚本可继承此脚本
 * */

let {ccclass, property} = cc._decorator;

//来自节点池的属性
class Pool_property {
    //ID位置
    constructor(id, pos) {
        this.id = id;
        this.pos = pos;
    }
}

module.exports = Pool_property;

/*采用节点池复用节点*/
@ccclass
class node_pool extends cc.Component {

    @property({type:cc.Prefab, displayName: '复用预制', tooltip: '此脚本子类如要重写ctor/constructor()或onDestroy() 请在重写内调用super方法;'})
    prefab = new cc.Prefab;

    //成员
    constructor() {
        super();
        this.Pool = new cc.NodePool();
        this.recordArray = [];
    }

    /**
     * @returns {cc.Node}
     */
    newPoolNode(parent = null) {
        let pool = null;
        let created = false;
        if (this.Pool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            pool = this.Pool.get();
            created = true;
        } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建
            pool = cc.instantiate(this.prefab);
        }
        const id = ICPC.lib.data_control.getRandId();
        const pos = this.recordArray.length;
        pool.pool_property = new Pool_property(id, pos);
        this.recordArray.push(pool);
        if (parent) {
            parent.addChild(pool);
            if (created && pool.getComponent) {
                let com = pool.getComponent(cc.Component);
                com.onLoad && com.onLoad();
                com.start && com.start();
            }
        }
        return pool;
    }

    getNodeOfId(id) {
        for (let node of this.getAllNodes()) {
            if (node.pool_property.id == id) {
                return node;
            }
        }
        return null;
    }

    getNodeOfPos(pos) {
        return this.recordArray[pos];
    }

    getAllNodes() {
        return this.recordArray;
    }

    deletePoolNode(node) {
        //
        console.log('删除', node);
        if (node['dataInfo']) {
            //坐标左移
            for (let i = node.pool_property.pos + 1; i < this.recordArray.length; i++) {
                this.recordArray[i].pool_property.pos--;
            }
            this.recordArray.splice(node.pool_property.pos, 1);
            node.dataInfo = null;
            this.Pool.put(node);
            console.log('长度', this.Pool.size());
        } else {
            console.error('删除出错', node);
        }
    }

    onDestroy() {
        while (this.recordArray.length > 0) {
            this.deletePoolNode(this.recordArray[0]);
        }
    }
}